<template>
  <div ref="pageComBox" class="NewCustomer page_wrapper">
    <div ref="otherBox">
      <Params ref="params" @search="channelCustomer" />
    </div>

    <el-table
      ref="multipleTable"
      :data="dataList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :max-height="tableHeight"
      :key="tableHeight"
      v-tabscroll="$getTableHeight"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="name" label="姓名" :width="sortTdWidth">
      </el-table-column>
      <el-table-column prop="mobile" label="电话" :width="smallWidth">
      </el-table-column>
      <el-table-column label="性别" :width="sortTdWidth">
        <template slot-scope="{ row }">
          {{ SEXTYPELIST[row.sex] }}
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" :width="sortTdWidth">
      </el-table-column>
      <el-table-column prop="city" label="城市" :width="sortTdWidth">
      </el-table-column>
      <el-table-column label="状态" :width="sortTdWidth">
        <template slot-scope="scope">
          {{
            followUpOptions[scope.row.progress] &&
            followUpOptions[scope.row.progress].label
          }}
        </template>
      </el-table-column>
      <el-table-column prop="employee.name" label="顾问" :width="sortTdWidth">
      </el-table-column>
      <el-table-column label="通话状态" :width="smallWidth">
        <template slot-scope="scope">
          {{ passOptions[scope.row.call] && passOptions[scope.row.call].label }}
        </template>
      </el-table-column>
      <el-table-column label="星级">
        <template slot-scope="scope">
          {{
            startOptions[scope.row.level] && startOptions[scope.row.level].label
          }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="条件备注" width="120">
      </el-table-column>
      <el-table-column label="跟进记录" width="400">
        <template slot-scope="scope">
          <el-popover placement="left-end" trigger="hover" width="500">
            <div class="remarkBox">
              <div class="remarkList">
                <div
                  class="item mb-3"
                  v-for="(item, index) in scope.row.remarkList"
                  :key="index"
                >
                  <div class="remark">{{ item.remark }}</div>
                  <div class="createBy pl-3">{{ item.createBy }}</div>
                  <div class="updateDate ml-3">{{ item.updateDate }}</div>
                </div>
              </div>
            </div>
            <div class="remarkList" slot="reference">
              <div
                class="item"
                :class="{ hide: index > 2 }"
                v-for="(item, index) in scope.row.remarkList"
                :key="index"
              >
                <div class="remark">{{ cutWordLength(item.remark, "17") }}</div>
                <div class="createBy pl-3">{{ item.createBy }}</div>
                <div class="updateDate ml-3">{{ item.updateDate }}</div>
              </div>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="未跟进时间" :width="smallWidth">
        <template slot-scope="scope">
          <div class="red">{{ scope.row.days }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="入库时间" width="160" />
      <el-table-column prop="distributeDate" label="分配日期" width="160" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" @click="followUpHandle(scope.row)"
            >跟进</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <BasePagination v-model="page" :total="totalCount" @change="pageOnChange" />
    <el-dialog
      title="跟进"
      width="60%"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-row>
        <el-col :xs="12" :sm="12">
          <el-input v-model="selectItem.name" readonly></el-input>
        </el-col>
        <el-col :push="1" :xs="10" :sm="10">
          <el-button type="primary" @click="callPhone(selectItem)"
            >一键拨号</el-button
          >
        </el-col>
      </el-row>
      <div class="txt">
        状态：{{
          followUpOptions[selectItem.progress] &&
          followUpOptions[selectItem.progress].label
        }}
      </div>
      <div class="txt">电话：{{ selectItem.mobile }}</div>
      <div class="txt">城市：{{ selectItem.city }}</div>
      <div class="txt">入库日期：{{ selectItem.createDate }}</div>
      <div class="txt">分配日期：{{ selectItem.distributeDate }}</div>
      <div class="d-flex" style="flex-wrap: wrap">
        <el-form :model="form" :inline="true" label-width="80px">
          <el-form-item
            :label="fieldItem.fieldName + ':'"
            v-for="(fieldItem, fieldIndex) in fieldList"
            :key="fieldIndex"
          >
            <div class="wrapping">
              <div v-if="fieldItem.type === 2">
                <el-select
                  v-model="selectItem['field' + (fieldIndex + 1)]"
                  clearable
                  :placeholder="fieldItem.fieldName"
                >
                  <el-option
                    v-for="item in fieldItem.value"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </div>
              <div v-else>
                <el-input
                  v-model="fieldItem.value1"
                  :placeholder="fieldItem.fieldName"
                ></el-input>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="btn">
        <el-button
          :loading="updateLoading"
          type="primary"
          @click="updateCustomer"
          >保存</el-button
        >
      </div>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>客户跟踪</span>
        </div>
        <div class="box d-flex">
          <div style="flex: 1" class="pr-3">
            <el-form ref="form" :model="form" label-width="80px">
              <el-form-item label="进度">
                <el-select
                  v-model="selectItem.progress"
                  clearable
                  placeholder="跟进状态"
                >
                  <el-option
                    v-for="item in followUpOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="通话状态">
                <el-select
                  v-model="selectItem.call"
                  clearable
                  placeholder="通话状态"
                >
                  <el-option
                    v-for="item in passOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="是否是有效客户">
                <el-select
                  v-model="selectItem.fit"
                  clearable
                  placeholder="是否有效"
                >
                  <el-option
                    v-for="item in effectiveOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="预约上门">
                <el-date-picker
                  v-model="value1"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择日期时间"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="星级">
                <el-select
                  v-model="selectItem.level"
                  clearable
                  placeholder="星级"
                >
                  <el-option
                    v-for="item in startOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="客户条件">
                <el-input
                  type="textarea"
                  :rows="5"
                  v-model="selectItem.remark"
                  placeholder="请输入内容"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :loading="updateLoading"
                  @click="updateCustomer"
                  >保存</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div style="flex: 1">
            <div class="remarkBoxCard">
              <div class="remarkList">
                <div
                  class="item mb-3"
                  v-for="(item, index) in selectItem.remarkList"
                  :key="index"
                >
                  <div class="remark">{{ item.remark }}</div>
                  <div class="createBy pl-3">{{ item.createBy }}</div>
                  <div class="updateDate ml-3">{{ item.updateDate }}</div>
                </div>
              </div>
            </div>
            <el-form ref="form" :model="form" label-width="80px">
              <el-form-item label="跟进记录">
                <el-input
                  type="textarea"
                  :rows="5"
                  v-model="input"
                  placeholder="请输入跟进记录，不超过50个字"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :loading="updateLoading"
                  @click="updateCustomer"
                  >保存</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="协助"
      width="30%"
      :visible.sync="chooseDialogVisi"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="选择协助人">
          <el-select
            v-model="helpEmployeeId"
            clearable
            placeholder="选择协助人"
          >
            <el-option
              v-for="item in employeeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="chooseDialogVisi = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="assistSubmitLoading"
          @click="assistSubmit"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Params from "./Params.vue";
import {
  channelCustomer,
  cancleHelp,
  updateCustomer,
  employeeList,
  helpCustomer,
} from "@/api/customer";
import {
  followUpOptions,
  startOptions,
  passOptions,
  effectiveOptions,
} from "./config";
import { mapState } from "vuex";
import { SEXTYPELIST } from "@/common/constants";
export default {
  components: { Params },
  data() {
    return {
      fieldList: [],
      page: 1,
      pageSize: 100,
      dataList: [],
      totalCount: 0,
      dialogFormVisible: false,
      form: {},
      followUpOptions,
      startOptions,
      passOptions,
      effectiveOptions,
      value1: "",
      selectItem: {},
      input: "",
      assistLoading: false,
      assistDisabled: true,
      chooseDialogVisi: false,
      updateLoading: false,
      employeeList: [],
      helpEmployeeId: "",
      assistSubmitLoading: false,
      sortTdWidth: 56,
      smallWidth: 110,
      tdWidth: 160,
      longTdWidth: 500,
      SEXTYPELIST,
      tableHeight: 0,
    };
  },
  mounted() {
    this.fieldList = JSON.parse(JSON.stringify(this.fieldList1));
    // 计算表格的高度
    let _this = this;
    this.$getTableHeight();
    window.onresize = function () {
      _this.$getTableHeight();
    };
  },
  computed: {
    ...mapState({
      fieldList1: (state) => state.myClient.fieldList,
    }),
  },
  watch: {
    fieldList1(val) {
      this.fieldList = JSON.parse(JSON.stringify(val));
    },
  },
  methods: {
    async channelCustomer(form) {
      this.showAppLoading();
      try {
        await channelCustomer({
          page: this.page,
          size: this.pageSize,
          paramObject: { ...form },
        }).then((res) => {
          const { data } = res;
          this.dataList = data.dataList || [];
          this.totalCount = data.totalCount;
          this.dataList.forEach((element) => {
            if (element.id === this.selectItem.id) {
              this.selectItem = element;
            }
          });
          this.$nextTick(() => {
            let index = 0;
            const list = document.querySelectorAll("tr");
            const tbody = document.querySelector("tbody");
            const comment = tbody.getElementsByClassName("comment");
            for (let index1 = comment.length - 1; index1 >= 0; index1--) {
              const element = comment[index1];
              element.remove();
            }
            list.forEach((dom) => {
              if (dom.classList.contains("el-table__row")) {
                console.log(this.dataList[index]);
                if (this.dataList[index].comment) {
                  const div = document.createElement("div");
                  div.innerHTML = `主管点评：${this.dataList[index].comment}`;
                  div.classList.add("comment");
                  dom.parentNode.insertBefore(div, dom);
                }
                index++;
              }
            });
          });
        });
        this.hideAppLoading();
      } catch (error) {
        this.hideAppLoading();
      }
    },
    pageOnChange(row) {
      this.page = row.page;
      if (row.pageSize) {
        this.pageSize = row.pageSize;
      }
      this.$refs.params.search();
    },
    addCustomerHandle() {
      this.$router.push({ name: "addClient" });
    },
    followUpHandle(item) {
      this.selectItem = Object.assign({}, item);
      this.value1 = item.appointmentDate;
      this.dialogFormVisible = true;
    },
    handleSelectionChange(e) {
      this.assistDisabled = e.length === 0;
      this.idArr = e.map((element) => element.id);
    },
    onSubmit() {},
    async assistHandle() {
      employeeList().then((res) => {
        this.employeeList = res.data;
      });
      this.chooseDialogVisi = true;
    },
    async assistSubmit() {
      this.assistSubmitLoading = true;
      try {
        await helpCustomer({
          idList: this.idArr,
          helpEmployeeId: this.helpEmployeeId,
        }).then((res) => {
          this.$message.success(res.message);
          this.chooseDialogVisi = false;
        });
        this.assistSubmitLoading = false;
      } catch (error) {
        this.assistSubmitLoading = false;
      }
    },
    cancleAssistHandle() {
      this.$confirm("确认取消协助?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "删除中...";
            try {
              await cancleHelp({ idList: this.idArr }).then((res) => {});
              done();
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "确定";
            } catch (error) {
              done();
              instance.confirmButtonLoading = false;
              instance.confirmButtonText = "确定";
            }
          } else {
            done();
          }
        },
      });
    },
    async updateCustomer() {
      // 编辑客户
      this.updateLoading = true;
      const { progress, id, level, remark, call, fit } = this.selectItem;
      const form = { progress, id, level, remark, call, fit };
      if (this.value1) {
        // 预约上门时间
        form.appointmentDate = this.value1;
      }
      for (const key in this.selectItem) {
        if (Object.hasOwnProperty.call(this.selectItem, key)) {
          if (key.indexOf("field") > -1) {
            form[key] = this.selectItem[key];
          }
        }
      }
      if (this.input) {
        form.customerRemark = { remark: this.input };
      }

      try {
        await updateCustomer(form).then((res) => {
          this.$refs.params.search();
          this.$message.success(res.message);
          this.input = "";
        });
        this.updateLoading = false;
      } catch (error) {
        this.updateLoading = false;
      }
    },
  },
};
</script>

<style>
.NewCustomer {
  padding: 20px;
}
.txt {
  padding: 8px 0;
}
.wrapping {
  margin-right: 10px;
  margin-bottom: 10px;
}
.btn {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}
</style>
